package xml.xstream;

/**
 * <pre>
 *   Title: XStream0.java
 *   Description: 
 *   Copyright: yundaex.com Copyright (c) 2013
 *   Company: 上海韵达货运有限公司
 * </pre>
 * 
 * @author liuzhaoqing
 * @version 1.0
 * @date 2014年10月23日
 */
import java.util.ArrayList;
import java.util.List;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.converters.SingleValueConverter;
 
class Blog {
    private Author writer;
    private List entries = new ArrayList();
 
    public Blog(Author writer) {
            this.writer = writer;
    }
 
    public void add(Entry entry) {
            entries.add(entry);
    }
 
    public List getContent() {
            return entries;
    }
}
 
class Author {
    private String name;
    public Author(String name) {
            this.name = name;
    }
    public String getName() {
            return name;
    }
}
 
class Entry {
    private String title, description;
    public Entry(String title, String description) {
            this.title = title;
            this.description = description;
    }
}

public class XStream1 {
   public static void main(String[] args) {
	   	Blog teamBlog = new Blog(new Author("Guilherme Silveira"));
        teamBlog.add(new Entry("first","My first blog entry."));
        teamBlog.add(new Entry("tutorial",
                "Today we have developed a nice alias tutorial. Tell your friends! NOW!"));
 
        XStream xstream = new XStream();
        xstream.alias("blog", Blog.class);
        xstream.alias("entry", Entry.class);
        
        xstream.aliasField("author", Blog.class, "writer");
        xstream.useAttributeFor(Blog.class, "writer");  
        //注册转换器  
        xstream.registerConverter(new AuthorConverter()); 

        // 使用隐式集合(Implicit Collection)
        xstream.addImplicitCollection(Blog.class, "entries");
        System.out.println(xstream.toXML(teamBlog));
   }
 
}

//定义一个转换器，如果使用，则需要在使用时注册到对应的XStream对象中
class AuthorConverter implements SingleValueConverter {
	/*该方法用于从Author对象中提取一个String字符串*/
	public String toString(Object obj) {
	      return ((Author) obj).getName();
	}
	/*该方法用于从一个String字符串生成Author对象*/
	public Object fromString(String name) {
	      return new Author(name);
	}
	/*该方法告诉XStream对象，该转换器可以转换哪种类型的对象*/
	public boolean canConvert(Class type) {
	      return type.equals(Author.class);
	}
}